// 天瑞云短信接口

package gcsms

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"

	"gitee.com/githubdog/goci/libraries/mylog"
)

// web http://cms.tinree.com/static/index.html#/user/login/tinree
// 15267893956
// bx112233

var (
	accesskey string = "CSYAKnpGeenjMEPO"
	secret    string = "OR2x3e0eqzdgvwod5hOvSMMvuStnLbjn"
)

// SendSmsCodeByTRY 发送验证码短信 - 天瑞云
func SendSmsCodeByTRY(mobile, code string) error {
	return normalSms("200044", mobile, code)
}

// SendConsignSms 发送寄拍排场短信
func SendConsignSms(mobile, datetime string) error {
	return normalSms("204620", mobile, datetime)
}

// SendAuctionCompleteSms 发送拍卖成交
func SendAuctionCompleteSms(mobile, name string, payOrderHour int) error {
	arr := []rune(name)
	if len(arr) > 10 {
		name = string(arr[:10]) + ".."
	}
	return normalSms("204621", mobile, fmt.Sprintf("%s##%d", name, payOrderHour))
}

func normalSms(templateid, mobile, content string) (err error) {
	url := "http://api.tinree.com/api/v2/single_send"
	data := map[string]string{
		"accesskey":  accesskey,
		"secret":     secret,
		"sign":       "239855",
		"templateId": templateid,
		"mobile":     mobile,
		"content":    content,
	}
	if byteData, e := json.Marshal(data); e == nil {
		if request, e := http.NewRequest(http.MethodPost, url, bytes.NewReader(byteData)); e == nil {
			request.Header.Add("Content-Type", "application/json;charset=UTF-8")
			if resp, e := http.DefaultClient.Do(request); e == nil {
				defer resp.Body.Close()
				if ret, e := ioutil.ReadAll(resp.Body); e == nil {
					mRet := map[string]string{}
					if err = json.Unmarshal(ret, &mRet); err == nil {
						if v, ok := mRet["code"]; !ok || v != "0" {
							if _, ok = mRet["msg"]; !ok {
								mRet["msg"] = "fail"
							}
							err = errors.New(mRet["msg"])
						}
					}
				} else {
					err = e
				}
			} else {
				err = e
			}
		} else {
			err = e
		}
	} else {
		err = e
	}
	if err != nil {
		mylog.WriteLog("sms", "", data, err)
	}
	return
}
